<template>
  <div class="release-container pt-4">
    <v-layout justify-start align-center wrap px-5>
      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 选择评测平台 -->
        <v-flex md4>
          <span
            class="subTitle title-color"
          >{{ $t('task.select') + $t('task.review') + $t('task.platform') }} *</span>
        </v-flex>
        <v-flex md8>
          <v-select solo :items="platforms" v-model="task.platform" hide-details></v-select>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 选择评测站点 -->
        <v-flex md4>
          <span
            class="subTitle title-color"
          >{{ $t('task.select') + $t('task.review') + $t('task.site') }} *</span>
        </v-flex>
        <v-flex md8>
          <v-select solo :items="sites" v-model="task.siteId"></v-select>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 店铺名称 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.shop') + $t('task.name') }} *</span>
        </v-flex>

        <v-flex md8>
          <!-- <v-text-field solo v-model="task.shopName"></v-text-field> -->
          <v-select solo :items="shopList" v-model="task.shopId"></v-select>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 选择产品类别 -->
        <v-flex md4>
          <span
            class="subTitle title-color"
          >{{ $t('task.select') + $t('task.product') + $t('task.category') }} *</span>
        </v-flex>
        <v-flex md8>
          <v-select solo :items="categories" v-model="task.category"></v-select>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品标题 (英文) -->
        <v-flex md4>
          <span
            class="subTitle title-color"
          >{{ $t('task.product') + $t('task.title') + $t('task.English') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.titleEnglish"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品标题 (中文) -->
        <v-flex md4>
          <span
            class="subTitle title-color"
          >({{ $t('task.product') + $t('task.title') + $t('task.Chinese') }})</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.titleChinese" counter="20"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品ASIN -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') }}ASIN *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.productAsin"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品价格 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') + $t('task.price') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.price"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品链接 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') + $t('task.link') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-textarea solo v-model="task.interlinkage"></v-textarea>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品主图 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') + $t('task.mainImage') }} *</span>
        </v-flex>

        <v-flex
          md8
          class="droppable elevation-4"
          id="dropPanel"
          @drop="onDrop"
          @dragover="onDragOver"
        >
          <div class="fill-height fill-width">
            <img class="preview-image" :src="imagePreview" alt v-if="imagePreview !== ''" />
          </div>

          <v-icon v-if="imagePreview === ''" class="cloud-icon" size="32">cloud_upload</v-icon>
          <span
            v-if="imagePreview === ''"
            class="upload-tip title-color"
          >{{ $t('task.selectFile') }}</span>

          <input
            type="file"
            accept="image/*"
            name="imageInput"
            class="file-input"
            @change="onFileInputChange"
          />
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 请输入关键字 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('login.pleaseEnter') + $t('task.keyword') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.keyword"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品位置 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('login.pleaseEnter') + $t('task.position') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.position"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 评测数量 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.review') + $t('task.count') }} *</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.amount" :hint="$t('task.reviewTip')"></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 wrap align-center justify-space-between>
        <!-- 增值费 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.extraFee') }}</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo v-model="task.addedFee" append-icon="attach_money" hide-details></v-text-field>
          <div class="text-xs-left added-tip mt-2">注: 可不填，想要快速接单，可增加增值费。</div>
        </v-flex>
      </v-flex>

      <v-flex md8 d-flex mt-3 align-center justify-space-between>
        <!-- 产品汇率 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') + $t('task.rate')}}</span>
        </v-flex>

        <v-flex md8>
          <v-text-field solo append-icon="attach_money" value="7.3" disabled></v-text-field>
        </v-flex>
      </v-flex>

      <v-flex md8 wrap d-flex align-center justify-space-between>
        <!-- 任务类型 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.task') + $t('task.type')}} *</span>
        </v-flex>

        <v-flex md8>
          <v-radio-group v-model="task.taskType">
            <v-radio
              v-for="(item, i) in taskTypes"
              :key="i"
              :label="item.text"
              :value="item.value"
              color="primary"
            ></v-radio>
          </v-radio-group>
        </v-flex>
      </v-flex>

      <v-flex md8 mt-2 d-flex align-center justify-space-between>
        <!-- 产品总价 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.product') + $t('task.totalPrice')}}</span>
        </v-flex>

        <v-flex md8>
          <div
            class="subTitle text-xs-left"
          >{{ `￥${totalPrice} (产品总价) = ${task.price} (产品价格) * ${task.amount} (数量) * ${rate} (汇率)` }}</div>
        </v-flex>
      </v-flex>
      <v-flex md8 mt-2 d-flex align-center justify-space-between>
        <!-- 服务费 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.service') + $t('task.fee')}}</span>
        </v-flex>

        <v-flex md8>
          <div
            class="subTitle text-xs-left"
          >{{ `￥${serviceFee} (服务费) = ${serviceFeeValue[task.taskType]} (服务费单价) * ${task.amount} (数量) + ${task.addedFee} (增值费单价) * ${task.amount} (数量)` }}</div>
        </v-flex>
      </v-flex>

      <v-flex md8 mt-2 d-flex align-center justify-space-between>
        <!-- 合计 -->
        <v-flex md4>
          <span class="subTitle title-color">{{ $t('task.total')}}</span>
        </v-flex>

        <v-flex md8>
          <div
            class="subTitle text-xs-left"
          >{{ `￥${summary} (合计) = ${totalPrice} (产品总价) + ${serviceFee} (服务费)` }}</div>
        </v-flex>
      </v-flex>

      <v-flex md8 mt-4>
        <small>{{ $t('base.requiredField') }}</small>
      </v-flex>

      <v-flex mt-4 md8 d-flex align-center justify-center>
        <v-flex md3>
          <v-btn large round color="primary" @click="onSubmit">
            <span class="title">{{ $t('base.submit')}}</span>
          </v-btn>
        </v-flex>
        <v-flex md2>
          <v-btn large round class="title" dark color="dark" @click="onReset">
            <span>{{ $t('base.reset')}}</span>
          </v-btn>
        </v-flex>
      </v-flex>
    </v-layout>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { TaskInfo, RespFileVo } from "@/api/bean";
import { Task, FileHandler, Shop } from "@/api";
import { Category, CategoryKV, ServiceFee, Rate } from "@/utils/constants";
import Cookie from "js-cookie";
declare const $Vue: Vue;

interface KV {
  text: string;
  value: any;
}

@Component({})
export default class ReleaseTask extends Vue {
  private platforms: Array<KV> = [
    {
      text: "Amazon",
      value: 1
    }
  ];

  private sites: Array<KV> = [
    {
      text: "USA",
      value: 1
    },
    {
      text: "France",
      value: 2
    }
  ];

  private categories: Array<KV> = CategoryKV.slice();

  private taskTypes: Array<KV> = [];

  private defaultTask: TaskInfo = {
    platform: 1,
    siteId: 1,
    shopName: "",
    category: 1,
    titleEnglish: "",
    titleChinese: "",
    productAsin: "",
    price: 1,
    interlinkage: "",
    productImg: "",
    keyword: "",
    position: "",
    amount: 1,
    addedFee: 0,
    taskType: 1,
    taskNumber: 1,
    taskStatus: 1,
    createUserId: Number(Cookie.get("seller_userId")),
    exchange: 7.3
  };

  private rate: number = Rate;

  // 校验
  private requiredFields = [
    "platform",
    "siteId",
    "shopId",
    "category",
    "titleEnglish",
    "titleChinese",
    "productAsin",
    "price",
    "interlinkage",
    "keyword",
    "position",
    "amount",
    "taskType"
  ];

  private imagePreview: string = "";

  private task: any = {};
  private imagefile: any = null;

  private serviceFeeValue: any = ServiceFee;

  private shopList: Array<KV> = [];

  protected mounted() {
    $Vue.$emit("title", { message: this.$t("base.releaseTask").toString() });

    this.getShopList();

    this.onReset();

    this.taskTypes = [
      {
        text: this.$t("task.type1").toString(),
        value: 1
      },
      {
        text: this.$t("task.type2").toString(),
        value: 2
      },
      {
        text: this.$t("task.type3").toString(),
        value: 3
      },
      {
        text: this.$t("task.type4").toString(),
        value: 4
      }
    ];
  }

  private get totalPrice(): any {
    let price = this.task.price;
    let amount = this.task.amount;
    let rate = Rate;
    let totalPrice = this.task.price * this.task.amount * rate;
    if (Number.isNaN(totalPrice)) {
      return "填写错误";
    }
    return totalPrice;
  }

  private get serviceFee(): any {
    let taskType = this.task.taskType;
    let service = Number(this.serviceFeeValue[taskType]);
    let amount = Number(this.task.amount);
    let addedFee = Number(this.task.addedFee);
    let serviceFee = (service + addedFee) * amount;
    if (Number.isNaN(serviceFee)) {
      return "填写错误";
    }
    return serviceFee;
  }

  private get summary() {
    return this.totalPrice + this.serviceFee;
  }

  private onDrop(ev: any) {
    ev.preventDefault();
    const file: File = ev.dataTransfer.files[0];
    if (!file.name.match(/\.jp(e)g|png/g)) {
      return alert("请拖入图片文件");
    }
    this.handleImageFile(file);
  }

  private onDragOver(ev: DragEvent) {
    ev.preventDefault();
    return false;
  }

  private onFileInputChange(ev: any) {
    let file = ev.target.files[0];
    this.handleImageFile(file);
  }

  private handleImageFile(file: File) {
    const reader = new FileReader();
    this.imagefile = file;
    // 使用base64上传
    reader.onload = (ev: any) => {
      this.imagePreview = ev.target.result;
    };
    reader.readAsDataURL(file);
  }

  /**
   * 图片上传完成
   */
  private handleImageUploaded(data: RespFileVo) {
    let fileUrl = data.fileUrl;
    this.task.productImg = data.fileUrl;
    this.imagefile = null;
    this.imagePreview = "";
    // 上传图片成功后发布新任务
    this.releaseTask();
  }

  /**
   * 处理店铺列表
   */
  private handleShopList(data: Array<any>) {
    let list: Array<KV> = [];
    data.forEach((item: any) => {
      // if (item.status === 2) {
      list.push({
        text: item.shopName,
        value: item.shopId
      });
      // }
    });
    this.shopList = list;
  }

  private onSubmit() {
    let pass = true;
    let message = "还有必填项目未填写.";
    this.requiredFields.forEach((item: string) => {
      if (!this.task[item] || this.task[item] === "") {
        pass = false;
      }
    });

    if (this.imagefile === null) {
      // pass = false;
      // message = "请选择产品主图.";
    }

    if (pass) {
      // 通过校验后上传文件
      let bjyx = sessionStorage.getItem("bjyx");
      
      if (this.summary > Number(bjyx)) {
        // $Vue.$emit("snackbar", {
        //   message: "余额不足"
        // });
        // this.$router.push({
        //   name: "充值"
        // });
        // return;

      }

      this.uploadFile();
      // this.releaseTask();
    } else {
      $Vue.$emit("snackbar", {
        message
      });
    }
  }

  private onReset() {
    this.task = Object.assign({}, this.defaultTask);
    // this.task = {
    //   platform: 1,
    //   siteId: 1,
    //   shopName: "JD",
    //   category: 1,
    //   titleEnglish: "Panini Maker",
    //   titleChinese: "煎饼",
    //   productAsin: "9023fsod",
    //   price: 13,
    //   interlinkage: "http://www.google.com",
    //   productImg: "",
    //   keyword: "sc",
    //   position: "234",
    //   amount: 10,
    //   addedFee: 13,
    //   taskType: 1,
    //   taskNumber: 1,
    //   taskStatus: 1,
    //   createUserId: Number(Cookie.get("seller_userId")),
    //   exchange: 7.3
    // };
  }

  private async releaseTask() {
    let shopName = "";
    this.shopList.forEach((item: any) => {
      if (item.value === this.task.shopId) {
        shopName = item.text;
      }
    });
    const params: TaskInfo = {
      ...this.task,
      shopName,
    };
    const { data } = await Task.releaseTask.r(params);
    console.log("releaseTask", data);

    if (data.result === 0) {
      $Vue.$emit("balance");
      this.onReset();
      // this.releaseTask(data.data.taskId);
      $Vue.$emit("snackbar", {
        message: data.message
      });
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
      this.$router.push({
        name: "充值"
      });
    }
  }

  private async uploadFile() {
    const params: FormData = new FormData();
    params.append("file", this.imagefile);
    const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    const { data } = await FileHandler.uploadFile.r(params, config);
    console.log("uploadFile", data);
    if (data.result === 0) {
      if (data.data.length > 0) {
        this.handleImageUploaded(data.data[0]);
      }
      // 图片上传完成后的处理
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 获取店铺列表
   */
  private async getShopList(queryForm?: any) {
    let params: any = {
      // limit: 1000,
      // offset: 0,
      checkStatus: 1,
      userId: Cookie.get("seller_userId"),
    };
    const { data } = await Shop.getShopList.r(params);
    console.log("getShopList", data);
    if (data.result === 0) {
      this.handleShopList(data.data.dataList);
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }
}
</script>

<style lang="less" scoped>
.droppable {
  border-radius: 4px;
  height: 8rem;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
  .preview-image {
    height: 100%;
  }
  .upload-tip {
    margin: 1rem;
  }
  .cloud-icon {
    margin-top: 2rem;
  }

  .file-input {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    left: 0;
    top: 0;
    &:hover {
      cursor: pointer;
    }
  }
}
#preview {
  height: 18rem;
  border: 1px dashed #888;
  border-radius: 8px;
}
.added-tip {
  font-size: 13px;
}
</style>


